package routers

import (
	"context"
	"dubbo.apache.org/dubbo-go/v3/config"
	_ "dubbo.apache.org/dubbo-go/v3/imports"
	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/common/utils"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
	"hertz/api"
	"hertz/pojo"
	"strconv"
	"time"
)

var commentProvider = new(api.CommentProviderClientImpl)
var favouriteProvider = new(api.FavouriteProviderClientImpl)
var messageProvider = new(api.MessageProviderClientImpl)
var relationProvider = new(api.RelationProviderClientImpl)
var userProvider = new(api.UserProviderClientImpl)
var videoProvider = new(api.VideoProviderClientImpl)

func OK(ctx *app.RequestContext, m map[string]interface{}) {
	h := utils.H{
		"status_code": 0,
		"status_msg":  "",
	}
	// 拼接
	for k, v := range m {
		h[k] = v
	}
	ctx.JSON(consts.StatusOK, h)
}

func FAIL(ctx *app.RequestContext, err error) {
	h := utils.H{
		"status_code": 1,
		"status_msg":  err.Error(),
	}
	ctx.JSON(consts.StatusOK, h)
}

func SetupRouter(h *server.Hertz) {
	h.GET("/hello", func(c context.Context, ctx *app.RequestContext) {
		ctx.JSON(consts.StatusOK, "Hello")
	})
	douyin := h.Group("/douyin")
	{
		loadComment(douyin)
		loadVideo(douyin)
		loadFavourite(douyin)
		loadMessage(douyin)
		loadRelation(douyin)
		loadUser(douyin)
	}
}

/**
 * 设置dubbo
 */
func init() {
	config.SetConsumerService(commentProvider)
	config.SetConsumerService(favouriteProvider)
	config.SetConsumerService(messageProvider)
	config.SetConsumerService(relationProvider)
	config.SetConsumerService(userProvider)
	config.SetConsumerService(videoProvider)
	if err := config.Load(); err != nil {
		panic(err)
	}
}

func transInt64(str string) int64 {
	int, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		return 0
	}
	return int
}

func transMessage(u *api.User, message *api.Message) pojo.Message {
	return pojo.Message{
		Id:         message.GetId(),
		Content:    message.GetContent(),
		CreateTime: time.Unix(message.GetCreateTime(), 0).Format("2006-01-02 15:04:05"),
	}
}

// TransVideo /** 在video中拼接user, 数量等， ？还要更改本地地址为http？
func transVideo(u *api.User, video *api.Video) pojo.Video {
	favouriteCount, _ := favouriteProvider.CountVideo(context.Background(), &api.Favourite{VideoId: video.GetId()})
	_, err := favouriteProvider.IsFavourite(context.Background(), &api.Favourite{VideoId: video.GetId(), UserId: u.GetId()})
	commentCount, _ := commentProvider.Count(context.Background(), &api.Comment{VideoId: video.GetId()})
	return pojo.Video{
		Id:             strconv.FormatInt(video.GetId(), 10),
		Author:         transUser(u, &api.User{Id: video.GetUserId()}),
		PlayUrl:        video.GetPlayUrl(),
		CoverUrl:       video.GetCoverUrl(),
		FavouriteCount: favouriteCount.Size,
		CommentCount:   commentCount.Size,
		IsFavorite:     err == nil,
		CreateTime:     video.CreateTime,
	}
}

// TransComment /** 在comment中拼接user
func transComment(u *api.User, comment *api.Comment) pojo.Comment {
	return pojo.Comment{
		Id:         comment.GetId(),
		User:       transUser(u, &api.User{Id: comment.UserId}),
		Content:    comment.GetContent(),
		CreateDate: time.Unix(comment.CreateTime, 0).Format("01-02"),
	}
}

// TransUser /** 通过传入的user的Id来生成， 其中判断u是否关注了user
func transUser(u *api.User, user *api.User) pojo.User {
	// 根据user.id查询用户
	find, _ := userProvider.Find(context.Background(), user)
	// 查询user的关注数
	countFollow, _ := relationProvider.CountFollow(context.Background(), &api.UserRelation{UserAId: user.GetId()})
	// 查询user的粉丝数
	countFollower, _ := relationProvider.CountFollower(context.Background(), &api.UserRelation{UserAId: user.GetId()})
	// 查询u是否关注user  没有错即为关注
	_, err := relationProvider.IsFollow(context.Background(), &api.UserRelation{UserAId: u.GetId(), UserBId: user.GetId()})

	return pojo.User{
		Id:            find.GetId(),
		FollowCount:   countFollow.GetSize(),
		FollowerCount: countFollower.GetSize(),
		IsFollow:      err == nil,
	}
}
